package com.app.controller;

import com.app.conf.RedisService;
import com.app.service.AdminUserService;
import com.app.service.DepartmentService;
import com.app.service.RoleService;
import com.app.model.*;
import com.app.util.*;
import com.app.vo.AdminUserVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.Producer;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@Controller
@RequestMapping("/api")
public class AdminUserController {
    @Autowired
    private Producer captchaProducer = null;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;


    @ResponseBody
    @RequestMapping("/captcha")
    public Result<Object> getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成验证码
        String capText = captchaProducer.createText();
//        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //向客户端写出
        UUID uuid = UUID.randomUUID();

        BufferedImage bi = captchaProducer.createImage(capText);//图形验证码字符流
        redisService.setStringKey(String.valueOf(uuid), capText);//redis中的key用uuid代替
        redisService.setExpire(String.valueOf(uuid), 120, TimeUnit.SECONDS);

        ServletOutputStream out = response.getOutputStream();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", stream);
        String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
        JSONObject data = new JSONObject();
        String base666 = "data:image/png;base64," + base64;
        data.put("key", uuid);
        data.put("code", base666);
        return Result.success(data);
//        try {
//            out.flush();
//        } finally {
//            out.close();
//        }
    }

    @PostMapping("/userLogin")
    public Result<Object> userLogin(
            @RequestBody JSONObject json,
//            @RequestParam("account") String account,
//            @RequestParam("pwd") String pwd,
//            @RequestParam("key") String key,
//            @RequestParam("code") String code,
            HttpServletRequest request) {
        String pwd = json.get("pwd").toString();
//        String key = json.get("key").toString();
//        String code = json.get("code").toString();
        String account = json.get("account").toString();
        String asePassWord = AESTool.dealAESEncrypt(pwd, "hwsc_pass");
//        String redissss = (String) redisService.getStringKey(key);
//        if (redisService.getStringKey(key) == null) {
//            return Result.error(500, "验证码已失效或已过期");
//        }
//        if (!redisService.getStringKey(key).equals(code)) {//通过key取value，然后进行比较，不直接进行判空
//            return Result.error(500, "验证码错误");
//        } else {
//            redisService.deleteKey(key);
//        }

        AdminUserModel user = adminUserService.getUserByUserName(account, asePassWord);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        if (user.getStatus() == 1) {
            String ip = IpUtil.getIpAddress(request);
            user.setLastIp(ip);
            user.setLastLoginTime(CommonHelp.getNowTimestamp());
            adminUserService.update(user);
            String token = TokenUtils.sign(String.valueOf(user.getId()));
            user.setToken(token);
            return Result.success(user);
        } else {
            return Result.error(500, "该账户已失效，请联系管理员处理");
        }

    }

    //    getAdminInfoByToken
    @GetMapping("/getAdminInfoByToken")//通过token查权限
    public Result<Object> getAdminInfoByToken(
            @RequestParam("token") String token,
            HttpServletRequest request) {
//        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
        List<String> roleModelList = new ArrayList<>();
        String[] roleArr = roleModel.getRules().split(";");//获取字符串
        if (roleArr != null) {
            for (int i = 0; i < roleArr.length; i++) {
                roleModelList.add(roleArr[i]);
            }
            user.setPermissionList(roleModelList);
        }

        return Result.success(user);
    }


    @GetMapping("/getUserList")//角色管理分页查询
    public Result<Object> getUserList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam("account") String account,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<AdminUserModel> userModelPage = adminUserService.getPageUserList(page, limit, account);
        for (int i = 0; i < userModelPage.getRecords().size(); i++) {
            RoleModel roleModel = roleService.getRoleByRoleId(userModelPage.getRecords().get(i).getRoles());
            userModelPage.getRecords().get(i).setRoleName(roleModel.getRoleName());
            DepartmentModel departmentModel = departmentService.getDepByDepId(userModelPage.getRecords().get(i).getDepartmentId());
            if (userModelPage.getRecords().get(i).getDepartmentId() == 0) {
                userModelPage.getRecords().get(i).setDepartmentName("超级管理员");
            } else {
                userModelPage.getRecords().get(i).setDepartmentName(departmentModel.getName());
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (userModelPage.getRecords().get(i).getLastLoginTime() != null) {
                String LastLoginTimeText = sdf.format(userModelPage.getRecords().get(i).getLastLoginTime());
                userModelPage.getRecords().get(i).setLastLoginTimeText(LastLoginTimeText);
            }
        }
        if (userModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) userModelPage.getTotal();
        List<AdminUserModel> userModelList;
        userModelList = userModelPage.getRecords();
        AdminUserVo vo = new AdminUserVo();
        vo.setCount(count);
        vo.setList(userModelList);
        return Result.success(vo);
    }

    @GetMapping("/updateUserStatus")//修改状态
    public Result<Object> updateStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel model = new AdminUserModel();
        model.setId(id);
        model.setStatus(status);
        adminUserService.update(model);
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除角色
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        AdminUserModel userModel = adminUserService.getUserByUserId(id);
        if (userModel == null) {
            return Result.error(500, "该管理员不存在");
        } else {
            adminUserService.delete(id);
            return Result.success(null);
        }
    }

    @PostMapping("/editAdminUser")//编辑角色
    public Result<Object> editAdminUser(
            @RequestBody AdminUserModel model,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        model.setStatus(1);
        if (model.getPwd() != null) {
            model.setPwd(AESTool.dealAESEncrypt(model.getPwd(), "hwsc_pass"));
        }
        if (model.getId() != null && model.getId() > 0) {
            model.setUpTime(CommonHelp.getNowTimestamp());
            adminUserService.update(model);

        } else {
            if (model.getDepartmentId() == null) {
                model.setDepartmentId(0);
            }
            model.setCrtTime(CommonHelp.getNowTimestamp());
            adminUserService.insert(model);
        }
        return Result.success(null);

    }

//    public static void main(String[] args) {
//        String asePassWord = AESTool.dealAESEncrypt("123456", "hwsc_pass");
//        System.out.println(asePassWord);
//        String s = AESTool.dealAESDecrypt("9777B0E167A3A17AE4323357B2047189", "hwsc_pass");
//        System.out.println(s);
//    }

}
